/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package it.unibo.as.client;

import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.HasHorizontalAlignment;
import com.google.gwt.user.client.ui.VerticalPanel;
import java.io.Serializable;
import java.util.List;
import net.zschech.gwt.comet.client.CometClient;
import net.zschech.gwt.comet.client.CometListener;
import net.zschech.gwt.comet.client.CometSerializer;
import net.zschech.gwt.comet.client.SerialTypes;

/**
 *
 * @author Johnny
 */
public class MainPanel extends Composite{

    private static VerticalPanel mainPanel;
    private static MenuGameBar menuBar;
    private static LoginForm loginForm;
    private static GamePanel gamePanel;
    private static CometClient cometClient;
    private static TableListPanel tableList;

    private static String user;



    @SerialTypes( { Message.class})
	public static abstract class ChatCometSerializer extends CometSerializer {
    }

    public MainPanel() {

        mainPanel = new VerticalPanel();
        menuBar = new MenuGameBar();
        loginForm = new LoginForm();

        gamePanel = new GamePanel();

        tableList = new TableListPanel();



        mainPanel.setSize("1024px", "748px");
        mainPanel.add(menuBar);

        mainPanel.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_CENTER);
        
        initWidget(mainPanel);
        

        AsyncCallback<String> callback = new AsyncCallback<String>() {
            @Override
            public void onSuccess(String result) {
                if(result==null){
                    menuBar.isLogged(Boolean.FALSE, null);

                    mainPanel.add(loginForm);
                }
                else{


                    user = result;
                    menuBar.isLogged(Boolean.TRUE, user);

                    com.google.gwt.user.client.Window.alert("GIA' LOGGATO!");
                
                    
                    mainPanel.add(gamePanel);
                    mainPanel.add(tableList);
                    tableList.center();
                    tableList.show();

                    SetupComet();

                }

            }

            @Override
            public void onFailure(Throwable caught) {
                loginForm.infoLabel.setText("Communication failed");
            }
        };

        getSignupService().isLogged(callback);

        

    }




    public void LoginClick() {

        String password;

        user = loginForm.loginBox.getText();
        password = loginForm.pwdBox.getText();

        AsyncCallback<Boolean> callbackLogin = new AsyncCallback<Boolean>() {
            @Override
            public void onSuccess(Boolean result) {
                if(result){
                    /* On success, remove loginForm, add gamePanel */
                    loginForm.removeFromParent();
                    mainPanel.add(gamePanel);

                    mainPanel.add(tableList);
                    tableList.center();
                    tableList.show();

                    menuBar.isLogged(Boolean.TRUE, user);

                    SetupComet();


                }
                else{
                    /* On failure, set error label */
                    
                    loginForm.infoLabel.setText("Wrong Username or Password.");
                }

            }

            @Override
            public void onFailure(Throwable caught) {
                loginForm.infoLabel.setText("Communication failed");
            }
        };

        

        


        getSignupService().login(user, password, callbackLogin);




    }

    public void LoginGoogleClick() {

    }

    public void SignupClick() {
        SignupPanel signDialog = new SignupPanel();
        signDialog.center();
        signDialog.show();
    }

    void signout() {
        AsyncCallback<Void> callback = new AsyncCallback<Void>() {

            @Override
            public void onFailure(Throwable caught) {
                com.google.gwt.user.client.Window.alert("A communication error occured while trying to sign out. Please try again.");
            }

            @Override
            public void onSuccess(Void result) {
                menuBar.isLogged(Boolean.FALSE, null);
                com.google.gwt.user.client.Window.Location.reload();
            }
        };


        getSignupService().signout(user,callback);

        throw new UnsupportedOperationException("Not yet implemented");
    }

    public static GWTAccountServiceAsync getSignupService() {
        // Create the client proxy. Note that although you are creating the
        // service interface proper, you cast the result to the asynchronous
        // version of the interface. The cast is always safe because the
        // generated proxy implements the asynchronous interface automatically.

        return GWT.create(GWTAccountService.class);
    }

    private void SetupComet() {
    CometSerializer serializer = GWT.create(ChatCometSerializer.class);

            cometClient = new CometClient(GWT.getModuleBaseURL() + "comet", serializer, new CometListener() {
            @Override
		public void onConnected(int heartbeat) {
			gamePanel.chatUpdate("COMET", "Connected");
                }

            @Override
		public void onDisconnected() {
                    gamePanel.chatUpdate("COMET", "Disconnected");
		}

            @Override
		public void onError(Throwable exception, boolean connected) {
                    gamePanel.chatUpdate("COMET", "error " + connected + " " + exception);
		}

            @Override
		public void onHeartbeat() {
			gamePanel.chatUpdate("COMET", "HeartBeat");
		}

            @Override
		public void onRefresh() {
			gamePanel.chatUpdate("COMET", "Refresh");
		}

            @Override
		public void onMessage(List<? extends Serializable> messages) {
			for (Serializable message : messages) {
				if (message instanceof Message) {
					Message m = (Message) message;
                                        gamePanel.chatUpdate(m.getUsername(),m.getMessage());
				}
                                /*
				else if (message instanceof StatusUpdate) {
					StatusUpdate statusUpdate = (StatusUpdate) message;
					output(statusUpdate.getUsername() + ": " + statusUpdate.getStatus(), "green");
				}
                                 * */

				else {
					gamePanel.chatUpdate("ERROR", "Unrecognized Comet Object");
				}
			}
		}
	});
		cometClient.start();
    }

}
